package com.mind.ridge.service.front.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mind.ridge.dto.front.OrderDto;
import com.mind.ridge.mapper.front.OrdersMapper;
import com.mind.ridge.pojo.front.*;
import com.mind.ridge.service.front.*;
import com.mind.ridge.utils.OrderException;
import com.mind.ridge.utils.R;
import com.sun.prism.impl.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author Mind
 */
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Resource
    private UserService userService;

    @Resource
    private AddressBookService addressBookService;

    @Resource
    private ShoppingCartService shoppingCartService;

    @Resource
    private OrderDetailService orderDetailService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<String> submit(HttpSession session, Orders order) throws OrderException {
        if (order == null) {
            return R.error("ERROR");
        }
        Long userId = (Long) session.getAttribute("userId");
        LambdaQueryWrapper<ShoppingCart> shoppingWrapper = new LambdaQueryWrapper<>();
        shoppingWrapper.eq(ShoppingCart::getUserId, userId);
        //查询购物车,判断该用户的购物车是否为空
        List<ShoppingCart> carts = shoppingCartService.list(shoppingWrapper);
        if (carts == null || carts.size() == 0) {
            throw new OrderException("购物车为空");
        }

        //查询用户地址，判断用户是否有地址
        Long addressBookId = order.getAddressBookId();
        LambdaQueryWrapper<AddressBook> bookWrapper = new LambdaQueryWrapper<>();
        bookWrapper.eq(AddressBook::getId, addressBookId);
        AddressBook addressBook = addressBookService.getOne(bookWrapper);
        if (addressBook == null) {
            throw new OrderException("收货地址为空");
        }
        order.setUserId(userId);
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getId, userId);

        //将用户信息插入到订单表中
        User user = userService.getOne(lqw);
        order.setPhone(user.getPhone());
        order.setUserName("zs");


        //设置收货人信息
        String consignee = addressBook.getConsignee();
        order.setConsignee(consignee);
        LocalDateTime now = LocalDateTime.now();
        order.setCheckoutTime(now);
        order.setOrderTime(now);
        order.setStatus(2);
        //设置订单号
        long orderId = IdWorker.getId();
        order.setNumber(orderId + "");


        AtomicInteger gross = new AtomicInteger(0);
        //将订单明细保存到OrderDetail表中
        List<OrderDetail> orderDetails = carts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setAmount(item.getAmount());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setImage(item.getImage());
            orderDetail.setName(item.getName());
            orderDetail.setAmount(item.getAmount());
            //计算总额
            gross.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        log.info("总价为：{}", gross);
        orderDetailService.saveBatch(orderDetails);
        //设置总额
        order.setAmount(new BigDecimal(gross.intValue()));
        this.save(order);

        //清空购物车
        shoppingCartService.remove(shoppingWrapper);

        return R.success("SUCCESS");
    }

    @Override
    public R<IPage<Orders>> userPage(int page, int pageSize, HttpSession session) {
        Long userId = (Long) session.getAttribute("userId");

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId, userId);
        lqw.orderByDesc(Orders::getOrderTime);
        IPage<Orders> userPage = this.page(new Page<>(page, pageSize), lqw);

        return R.success(userPage);
    }

    @Override
    public R<IPage<OrderDto>> orderPage(int page, int pageSize) {
        IPage<Orders> orders = new Page<>(page, pageSize);
        this.page(orders);
        IPage<OrderDto> dtoIPage = new Page<>(page, pageSize);
        List<OrderDto> list = orders.getRecords().stream().map((item) -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(item, orderDto);
            LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AddressBook::getId, item.getAddressBookId());
            AddressBook address = addressBookService.getOne(wrapper);
            orderDto.setAddress(address.getDetail());
            return orderDto;
        }).collect(Collectors.toList());
        BeanUtils.copyProperties(orders, dtoIPage, "records");
        dtoIPage.setRecords(list);
        return R.success(dtoIPage);
    }

    @Override
    public R<String> changeOrderStatus(Orders order) {

        if (order == null) {
            return R.error("订单不存在");
        }
        Orders orders = this.getById(order.getId());
        if (orders == null) {
            return R.error("出错了");
        }
        //更新订单状态
        orders.setStatus(order.getStatus());
        this.updateById(orders);
        return R.success("SUCCESS");
    }

    @Override
    public R<String> again(Orders orders, HttpSession session) {
        String id = String.valueOf(orders.getId());
        if (!Strings.isNotEmpty(id)) {
            return R.error("ERROR");
        }
        Orders order = this.getById(id);
        if (order == null) {
            return R.error("该订单异常");
        }
        //获取订单号
        String orderId = order.getNumber();
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        //通过订单号获取订单详细信息
        lqw.eq(OrderDetail::getOrderId, orderId);
        List<OrderDetail> list = orderDetailService.list(lqw);
        Long userId = (Long) session.getAttribute("userId");

        //将获取到的信息添加到购物车
        List<ShoppingCart> newCart = list.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setUserId(userId);
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setImage(item.getImage());
            shoppingCart.setSetmealId(item.getSetmealId());
            shoppingCart.setDishId(item.getDishId());
            return shoppingCart;
        }).collect(Collectors.toList());
        //将购物车数据保存到数据库中
        shoppingCartService.saveBatch(newCart);
        return R.success("SUCCESS");
    }
}
